package lib.bone.flow.module.processor;

import cn.hutool.core.lang.Validator;
import lib.bone.flow.constant.FlowWorkStatusConst;
import lib.bone.flow.domain.dto.FlowParam;
import lib.bone.flow.domain.entity.FlowWork;
import lib.bone.flow.domain.model.*;
import lib.bone.flow.service.FlowWorkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: kindear
 */
@Slf4j
@Service
public class FlowNodeProcessorCtl {
    @Autowired(required=false)
    private List<FlowNodeProcessor> flowNodeProcessorList;

    @Autowired
    FlowWorkService flowWorkService;

    /**
     * 节点流程处理器控制
     * @param flowWork
     * @param flowModel
     * @param baseModel
     * @param flowParam
     */
    public void process(FlowWork flowWork, FlowModel flowModel, BaseModel baseModel, FlowParam flowParam){
        //log.info("开始执行"+baseModel.getNodeType());
        // 判断当前节点是否为空
        if(Validator.isEmpty(baseModel)) return;
        // 执行开始节点
        for (FlowNodeProcessor processor:flowNodeProcessorList){
            if (processor.getNodeType().equals(baseModel.getNodeType())){
                // 获取下一个节点
                BaseModel nextNodeModel = flowModel.getNodeModel(baseModel.getNextNodeId());
                if (baseModel instanceof StartModel){
                    // 开始节点 -- 执行开始模型
                    processor.process(flowWork,flowModel,baseModel,flowParam);
                    // 执行下一个模型
                    log.info("遍历执行");
                    process(flowWork,flowModel,nextNodeModel,flowParam);
                }else if (baseModel instanceof EndModel){
                    // 结束节点 -- 执行结束模型
                    // 1. 更新work 状态 挂起实例
                    flowWork.setStatus(0);
                    // 2. 更新实例状态为已完成
                    flowWork.setFlowWorkStatus(FlowWorkStatusConst.FINISHED);
                    // 3. 进行下一节点
                    flowWork.setCurrentNodeId(baseModel.getId());
                    flowWork.setNextNodeId("");
                    flowWork.setLastOperator(flowParam.getOperator());
                    processor.process(flowWork,flowModel,baseModel,flowParam);
                  //  process(flowWork,flowModel,baseModel,flowParam);
                    // 写入更新
                    flowWorkService.updateWork(flowWork);
                }else if (baseModel instanceof TaskModel){
                    log.info("调用TASK节点");
                    processor.process(flowWork,flowModel,baseModel,flowParam);
                    // 任务节点
                    flowWork.setCurrentNodeId(baseModel.getId());
                    flowWork.setNextNodeId(baseModel.getNextNodeId());
                    flowWork.setLastOperator(flowParam.getOperator());
                    // 写入更新
                    flowWorkService.updateWork(flowWork);
                }
                break;
            }
        }
    }

}
